//
//  ProductDetail.m
//  cutter
//
//  Created by mac on 16/1/11.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "UserCenterPick.h"
#import "ProductCustom.h"
#import "ProductDetailCtrl.h"
#import "MBProgressHUD.h"

//产品详细弹出
@implementation ProductSynopsisCtrl
- (void)viewDidLoad{
    [super viewDidLoad];
    //
    if (self.data) {
        __weak ProductSynopsisCtrl *this = self;
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [this setDetail:[[AppData productDetail:[this.data objectForKey:@"id"]] firstObject]];
            [this.detail setValue:@"0" forKey:@"schemeType"];
            [this.detail setValue:@"product" forKey:@"t"];
            [AppData productAttribute:this.detail all:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:this.view animated:YES];
                [this reloadData];
            });
        });
    }
}
- (void)reloadData{
    [AppData loadImage:[self.detail objectForKey:@"thumb400_jpg"] view:self.imageView];
    //材质颜色
    NSMutableArray *colorname = [NSMutableArray array];
    NSMutableArray *materialname = [NSMutableArray array];
    NSArray *materials = [[[self.detail objectForKey:@"model_info"] objectForKey:@"model"] objectForKey:@"material"];
    for (id material in materials) {
        id cn = [material objectForKey:@"colorname"];
        if (cn && cn != [NSNull null]) {
            [colorname addObject:cn];
        }
        id mn = [material objectForKey:@"materialname"];
        if (mn && mn != [NSNull null]) {
            [materialname addObject:mn];
        }
    }
    //
    NSMutableString *text = [NSMutableString string];
    if (isEmpty([self.detail objectForKey:@"productsn"]) == NO) {
        [text appendString:[AppData objToString:[self.detail objectForKey:@"productsn"] lable:@"型号："]];
        [text appendString:@"<br/>"];
    }
    if (isEmpty([self.detail objectForKey:@"size"]) == NO) {
        [text appendString:[AppData sizeToString:[self.detail objectForKey:@"size"] lable:@"规格："]];
        [text appendString:@"<br/>"];
    }
    if (isEmpty([self.detail objectForKey:@"catename"]) == NO) {
        [text appendString:[AppData objToString:[self.detail objectForKey:@"catename"] lable:@"品类："]];
        [text appendString:@"<br/>"];
    }
    if (isEmpty([self.detail objectForKey:@"stylename"]) == NO) {
        [text appendString:[AppData objToString:[self.detail objectForKey:@"stylename"] lable:@"风格："]];
        [text appendString:@"<br/>"];
    }
    if (isEmpty(materialname) == NO) {
        [text appendString:[AppData objToString:materialname lable:@"材质："]];
        [text appendString:@"<br/>"];
    }
    if (isEmpty(colorname) == NO) {
        [text appendString:[AppData objToString:colorname lable:@"颜色："]];
    }
    //
    NSString *html = @"";
    html = [html stringByAppendingFormat:@"<span style=\"line-height:200%%;font-size:16px;color:#4A4A4A\">%@<br/></span>",[self.detail objectForKey:@"productname"]];
    html = [html stringByAppendingFormat:@"<span style=\"line-height:150%%;font-size:24px;color:#4794EF\">%@<br/></span>",[AppData priceToString:[self.detail objectForKey:@"price"] lable:nil]];
    html = [html stringByAppendingFormat:@"<span style=\"line-height:200%%;font-size:14px;color:#4A4A4A\">%@</span>",text];
    //
    NSDictionary *options = [NSDictionary dictionaryWithObject:NSHTMLTextDocumentType forKey:NSDocumentTypeDocumentAttribute];
    NSAttributedString * aa = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil];
    [self.textView setAttributedText:aa];
    //
    [self.data setValue:@"product" forKey:@"t"];
    NSDictionary *client = [TMGlobal valueForKey:@"client"];
    id fav = [AppData userHaveFavorite:self.data client:client];
    if (fav) {
        [self.addFavorite setSelected:YES];
    }else{
        [self.addFavorite setSelected:NO];
    }
}
-(IBAction)exitTouch:(id)sender {
    if (self.presentingViewController) {
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    }
}
-(void)addFavoriteTouch:(UIButton*)sender{
    NSDictionary *client = [TMGlobal valueForKey:@"client"];
    id fav = [AppData userHaveFavorite:self.data client:client];
    if (fav) {
        [sender setSelected:NO];
    }else{
        [sender setSelected:YES];
    }
    if (sender.selected) {
        if ([AppData userEditFavorite:self.data client:client]) {
            [TMAlert showAtView:self.view image:@"img_Prompt_Favorites_OK.png"];
        }
    }else{
        if ([AppData userDeleteFavorite:self.data client:client]) {
            [TMAlert showAtView:self.view image:@"img_Prompt_Favorites_Cancel.png"];
        }
    }
}
//
-(void)addCartTouch:(UIButton*)sender{
    NSDictionary *client = [TMGlobal valueForKey:@"client"];
    if ([AppData userAddCart:self.data client:client]) {
        [TMAlert showAtView:self.view image:@"img_Prompt_ShoppingCar_OK.png"];
    }
}
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if ([TMGlobal valueForKey:@"client"]) {
        if ([identifier isEqualToString:@"favoriteSegue"]) {
            [self addFavoriteTouch:sender];
        }
        if ([identifier isEqualToString:@"cartSegue"]) {
            [self addCartTouch:sender];
        }
        return NO;
    }
    return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender{
    __weak ProductSynopsisCtrl *this = self;
    if ([segue.destinationViewController isKindOfClass:ProductDetailCtrl.class]) {
        ProductDetailCtrl *ctrl = segue.destinationViewController;
        [ctrl setData:self.data];
    }
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:UserCenterSelect.class]) {
            UserCenterSelect *root = [ctrl.viewControllers firstObject];
            [root setOnSelected:^(id target, id result){
                [ctrl dismissViewControllerAnimated:YES completion:^{
                    if (result) {
                        if ([segue.identifier isEqualToString:@"favoriteSegue"]) {
                            [this addFavoriteTouch:sender];
                        }
                        if ([segue.identifier isEqualToString:@"cartSegue"]) {
                            [this addCartTouch:sender];
                        }
                    }
                }];
            }];
        }
    }
}
@end


@interface ProductDetailCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ProductDetailCell
-(void)setSelected:(BOOL)selected{
    [super setSelected:selected];
    if (selected) {
        [self setBorderWidth:2];
    }else{
        [self setBorderWidth:0];
    }
}
@end


//
@implementation ProductContentViewCell
- (void)awakeFromNib{
    [super awakeFromNib];
    //
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTouch:)];
    [self.imageView addGestureRecognizer:tap];
    [tap setCancelsTouchesInView:NO];
}
- (void)tapTouch:(id)sender{
    if (self.hiddenInfo.constant!=0) {
        [self.hiddenInfo setConstant:0];
        [self.hiddenThumb setConstant:8];
    }else{
        [self.hiddenInfo setConstant:-335];
        [self.hiddenThumb setConstant:-68];
    }
    [self updateConstraintsIfNeeded];
    //
    [UIView beginAnimations:nil context:nil];
    [self layoutIfNeeded];
    [UIView commitAnimations];
}
- (void)reset{
    [self setDetail:nil];
    [self.textView setText:@""];
    [self.priceView setText:@""];
    [self.collectionView reloadData];
    [self.addFavorite setSelected:NO];
    [self.imageView.imageView setImage:nil];
    [self.addFavorite setUserInteractionEnabled:NO];
    [self.addCart setUserInteractionEnabled:NO];
    //
    [self.hiddenInfo setConstant:0];
    [self.hiddenThumb setConstant:8];
    [self updateConstraintsIfNeeded];
}
- (void)reloadData{
    if (self.data && self.detail==nil) {
        [self.data setValue:@"product" forKey:@"t"];
        //
        __weak ProductContentViewCell *this = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [this setDetail:[[AppData productDetail:[this.data objectForKey:@"id"]] firstObject]];
            [this.detail setValue:@"0" forKey:@"schemeType"];
            [this.detail setValue:@"product" forKey:@"t"];
            [AppData productAttribute:this.detail all:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [this updateAll];
            });
        });
    }
}
- (void)updateAll{
    if (self.detail) {
        //材质颜色
        NSMutableArray *colorname = [NSMutableArray array];
        NSMutableArray *materialname = [NSMutableArray array];
        NSArray *materials = [[[self.detail objectForKey:@"model_info"] objectForKey:@"model"] objectForKey:@"material"];
        for (id material in materials) {
            id cn = [material objectForKey:@"colorname"];
            if (cn && cn != [NSNull null]) {
                [colorname addObject:cn];
            }
            //
            id mn = [material objectForKey:@"materialname"];
            if (mn && mn != [NSNull null]) {
                [materialname addObject:mn];
            }
        }
        //
        NSMutableString *text = [NSMutableString string];
        if (isEmpty([self.detail objectForKey:@"productsn"]) == NO) {
            [text appendString:[AppData objToString:[self.detail objectForKey:@"productsn"] lable:@"型号："]];
            [text appendString:@"\n\n"];
        }
        if (isEmpty([self.detail objectForKey:@"size"]) == NO) {
            [text appendString:[AppData sizeToString:[self.detail objectForKey:@"size"] lable:@"规格："]];
            [text appendString:@"\n\n"];
        }
        if (isEmpty([self.detail objectForKey:@"catename"]) == NO) {
            [text appendString:[AppData objToString:[self.detail objectForKey:@"catename"] lable:@"品类："]];
            [text appendString:@"\n\n"];
        }
        if (isEmpty([self.detail objectForKey:@"stylename"]) == NO) {
            [text appendString:[AppData objToString:[self.detail objectForKey:@"stylename"] lable:@"风格："]];
            [text appendString:@"\n\n"];
        }
        if (isEmpty([self.detail objectForKey:@"spacename"]) == NO) {
            [text appendString:[AppData objToString:[self.detail objectForKey:@"spacename"] lable:@"空间："]];
            [text appendString:@"\n\n"];
        }
        if (isEmpty([self.detail objectForKey:@"processingname"]) == NO) {
            [text appendString:[AppData objToString:[self.detail objectForKey:@"processingname"] lable:@"工艺："]];
            [text appendString:@"\n\n"];
        }
        if (isEmpty([self.detail objectForKey:@"installationname"]) == NO) {
            [text appendString:[AppData objToString:[self.detail objectForKey:@"installationname"] lable:@"安装方式："]];
            [text appendString:@"\n\n"];
        }
        if (isEmpty(materialname) == NO) {
            [text appendString:[AppData objToString:materialname lable:@"材质："]];
            [text appendString:@"\n\n"];
        }
        for (id item in [self.detail objectForKey:@"attributes"]) {
            id val = [item objectForKey:@"option"];
            if (val) {
                if([val isKindOfClass:NSArray.class]){
                    [text appendFormat:@"%@：%@\n\n", [item objectForKey:@"name"], [val componentsJoinedByString:@","]];
                }else{
                    [text appendFormat:@"%@：%@\n\n", [item objectForKey:@"name"], val];
                }
            }
        }
        if (isEmpty([self.detail objectForKey:@"content"]) == NO) {
            NSString *str = [self.detail objectForKey:@"content"];
            NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:@"<[^>]+>" options:NSRegularExpressionCaseInsensitive error:nil];
            str = [regular stringByReplacingMatchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, [str length]) withTemplate:@""];
            [text appendString:[AppData objToString:str lable:@"说明："]];
        }
        //
        [self.textView setText:text];
        [self.collectionView reloadData];
        [self.priceView setText:[AppData priceToString:[self.detail objectForKey:@"price"] lable:nil]];
        //
        if ([[self.detail objectForKey:@"images"] count] > 0) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
            [self collectionView:self.collectionView didSelectItemAtIndexPath:indexPath];
            [self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        }
        //
        NSDictionary *client = [TMGlobal valueForKey:@"client"];
        id fav = [AppData userHaveFavorite:self.data client:client];
        if (fav) {
            [self.addFavorite setSelected:YES];
        }else{
            [self.addFavorite setSelected:NO];
        }
        [self.addFavorite setUserInteractionEnabled:YES];
        [self.addCart setUserInteractionEnabled:YES];
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.detail) {
        return [[self.detail objectForKey:@"images"] count];
    }
    return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    id item = [[self.detail objectForKey:@"images"] objectAtIndex:indexPath.item];
    ProductDetailCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    [AppData loadImage:[item objectForKey:@"thumb400_jpg"] view:cell.imageView];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    id item = [[self.detail objectForKey:@"images"] objectAtIndex:indexPath.item];
    [AppData loadImage:[item objectForKey:@"pic_jpg"] view:self.imageView.imageView];
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    CGFloat tw = [[self.detail objectForKey:@"images"] count] * 70 - 10;
    if (tw < collectionView.bounds.size.width) {
        CGFloat s = (collectionView.bounds.size.width - tw ) / 2;
        return UIEdgeInsetsMake(0, s, 0, s);
    }
    return UIEdgeInsetsZero;
}
@end


//产品详细
@implementation ProductDetailCtrl
- (void)viewDidLoad{
    [super viewDidLoad];
    [self.addScheme setHidden:self.type != 1];
    [self.addScheme addTarget:self action:@selector(addSchemeTouch:) forControlEvents:UIControlEventTouchUpInside];
    if(!self.addScheme.hidden){
        self.menuView.favbtn.hidden = YES;
        self.menuView.cartbtn.hidden = YES;
        self.menuView.tempbtn.hidden = YES;
        self.menuView.iconView.hidden = YES;
        self.menuView.nameView.hidden = YES;
    }else{
        self.menuView.favbtn.hidden = NO;
        self.menuView.cartbtn.hidden = NO;
        self.menuView.tempbtn.hidden = NO;
        self.menuView.iconView.hidden = NO;
        self.menuView.nameView.hidden = NO;
    }
    self.menuView.searchbtn.hidden = YES;
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    //
    if (NO == CGRectEqualToRect(self.view.frame, self.frame)) {
        [self setFrame:self.view.frame];
        //
        NSInteger index = [self indexOfObject:self.data];
        if (index == NSNotFound) {
            if (self.data) {
                [self.source addObject:self.data];
            }
            index = 0;
        }
        //
        [self.collectionView reloadData];
        if ([self.source count] > 0) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        }
    }
    
}
//
-(NSMutableArray *)source{
    if (_source == nil) {
        [self setSource:[NSMutableArray array]];
    }
    return _source;
}
-(NSInteger)indexOfObject:(id)object{
    for (NSInteger i=0;i<[self.source count];i++) {
        id temp = [self.source objectAtIndex:i];
        if ([[temp objectForKey:@"id"] isEqual:[self.data objectForKey:@"id"]]) {
            return i;
        }
    }
    return NSNotFound;
}
-(id)findCell:(UIView*)view{
    UIView *cell = view;
    while (cell) {
        if ([cell isKindOfClass:ProductContentViewCell.class]) {
            return cell;
        }
        cell = [cell superview];
    }
    return nil;
}
-(id)currentCell{
    int page = roundf(self.collectionView.contentOffset.x / self.collectionView.frame.size.width);
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:page inSection:0];
    return [self.collectionView cellForItemAtIndexPath:indexPath];
}
//
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    ProductContentViewCell *cell=[self currentCell];
    if (cell) {
        [self.titleView setText:[AppData objToString:[cell.data objectForKey:@"productname"] lable:nil]];
        [cell reloadData];
    }
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (decelerate == NO) {
        [self scrollViewDidEndDecelerating:scrollView];
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.source count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    id item = [self.source objectAtIndex:indexPath.item];
    ProductContentViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifler" forIndexPath:indexPath];
    if ([[collectionView indexPathsForVisibleItems] count] == 0) {
        [self.titleView setText:[AppData objToString:[item objectForKey:@"productname"] lable:nil]];
        [cell setData:item];
        [cell reloadData];
    }else{
        [cell setData:item];
        [cell reset];
    }
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return collectionView.frame.size;
}
//
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if ([TMGlobal valueForKey:@"client"]) {
        if ([identifier isEqualToString:@"favorite"]) {
            [TMGlobal setValue:@(3) forKey:@"clientTag"];
            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
            return NO;
        }
        if ([identifier isEqualToString:@"cart"]) {
            [TMGlobal setValue:@(4) forKey:@"clientTag"];
            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
            return NO;
        }
        if ([identifier isEqualToString:@"client"]) {
            [TMGlobal setValue:nil forKey:@"clientTag"];
            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
            return NO;
        }
        if ([identifier isEqualToString:@"favoriteSegue"]) {
            [self addFavoriteTouch:sender];
        }
        if ([identifier isEqualToString:@"cartSegue"]) {
            [self addCartTouch:sender];
        }
        return NO;
    }
    return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __weak ProductDetailCtrl *this = self;
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:UserCenterSelect.class]) {
            UserCenterSelect *root = [ctrl.viewControllers firstObject];
            [root setOnSelected:^(id target, id result){
                [ctrl dismissViewControllerAnimated:YES completion:^{
                    if(result){
                        if([segue.identifier isEqualToString:@"favorite"]){
                            [TMGlobal setValue:@(3) forKey:@"clientTag"];
                            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
                        }
                        if([segue.identifier isEqualToString:@"cart"]){
                            [TMGlobal setValue:@(4) forKey:@"clientTag"];
                            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
                        }
                    }
                }];
            }];
        }
        if ([[ctrl.viewControllers firstObject] isKindOfClass:UserCenterSelect.class]) {
            UserCenterSelect *root = [ctrl.viewControllers firstObject];
            [root setOnSelected:^(id target, id result){
                [ctrl dismissViewControllerAnimated:YES completion:^{
                    if(result){
                        if ([segue.identifier isEqualToString:@"favoriteSegue"]) {
                            [this addFavoriteTouch:sender];
                        }
                        if ([segue.identifier isEqualToString:@"cartSegue"]) {
                            [this addCartTouch:sender];
                        }
                    }
                }];
            }];
        }
    }
}
-(IBAction)exitTouch:(id)sender {
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
-(void)addSchemeTouch:(UIButton*)sender{
    if (self.onSelected) {
        ProductContentViewCell *cell = [self currentCell];
        if (cell) {
            self.onSelected(self, cell.detail);
        }
    }
}
-(void)addFavoriteTouch:(UIButton*)sender{
    ProductContentViewCell *cell = [self findCell:sender];
    if (cell) {
        NSDictionary *client = [TMGlobal valueForKey:@"client"];
        id fav = [AppData userHaveFavorite:cell.data client:client];
        if (fav) {
            [sender setSelected:NO];
        }else{
            [sender setSelected:YES];
        }
        if (sender.selected) {
            if ([AppData userEditFavorite:cell.data client:client]) {
                [TMAlert showAtView:self.view image:@"img_Prompt_Favorites_OK.png"];
            }
        }else{
            if ([AppData userDeleteFavorite:cell.data client:client]) {
                [TMAlert showAtView:self.view image:@"img_Prompt_Favorites_Cancel.png"];
            }
        }
    }
}
-(void)addCartTouch:(UIButton*)sender{
    ProductContentViewCell *cell = [self findCell:sender];
    if (cell) {
        NSDictionary *client = [TMGlobal valueForKey:@"client"];
        if ([AppData userAddCart:cell.detail client:client]) {
            [TMAlert showAtView:self.view image:@"img_Prompt_ShoppingCar_OK.png"];
        }
    }
}
@end
